package com.smart.primary.util;

import com.smart.primary.util.creat.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class ListUtil {

    public static List quChong(List list){
        return new ArrayList( new HashSet(list));
    }

    public static String toStr(List list){
       return StringUtils.join(list,",");
    }

    public static String toStr(List list,String param){
        return StringUtils.join(list,param);
    }

    public static List<String> toList(String str,String param){
        if(str==null || param==null){
            return null;
        }
        return new ArrayList(Arrays.asList(str.split(param)));
    }

    public static List<String> toList(String str){
        return toList(str,",");
    }

    public static List<String> listToStrList(List list,String param){
        if (list.size()==0 || StringUtils.isBlank(param)) {
            return new ArrayList<String>();
        }
        StringBuilder result=new StringBuilder();
        for (Object obj : list) {
            Field[] field = FieldUtils.getAllFields(obj.getClass());
            for (Field fe : field) {
                if(fe.getName().equals(param)){
                    try {
                        //设置为允许访问
                        fe.setAccessible(true);
                        String str="";
                        if(fe.get(obj)!=null){
                            if(StringUtils.isNotBlank(StrUtil.trim(fe.get(obj).toString()))){
                                str= StrUtil.trim(fe.get(obj).toString())+",";
                            }
                        }
                        result.append(str);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        return StrUtil.strToList(result.substring(0,result.length()-1));
    }
}
